from sympy import solve, latex, N
import sys
sys.path.append("/home/sivan/0_0/projects/gitee/others")
from latex2sympy.process_latex import process_sympy
from pydantic import BaseModel

class Eq_model(BaseModel):
    expr: str
    unns: list

def transEqs(expr):
    elist = expr.split('\n')
    begin = 0
    end = len(elist)
    for i in range(end):
        if '\\begin' in elist[i]: begin = i + 1
        if '\\end' in elist[i]: end = i
    if 0 == begin or end == len(elist): return '方程组输入格式错误!'
    elist = elist[begin: end]
    result = []
    for i in elist:
        i = i.strip()
        if i.endswith(r'\\'): i = i[:-2]
        try: result.append(process_sympy(i))
        except: return '错误的方程格式: ' + str(i)
    return result

def eq(data):
    expr = data.expr
    unns = data.unns
    result = {'latex': '', 'text': '', 'float': '', 'error': ''}
    if None == expr or '' == expr.strip():
        result['error'] = '请输入方程!'
        return result
    uLen = len(unns)
    if uLen > 1:
        exprs = transEqs(expr)
        if type(exprs) is str:
            result['error'] = exprs
            return result
    elif 1 == uLen:
        unns = unns[0]
        try: exprs = process_sympy(expr)
        except:
            result['error'] = '错误的方程格式: ' + str(expr)
            return result
    else:
        result['error'] = '未知数输入错误!'
        return result
    try: ansr = solve(exprs, unns)
    except:
        result['error'] = '解方程时出错: ' + str(exprs)
        return result
    result['latex'] = latex(ansr)
    result['text'] = str(ansr)
    rstFlt = ''
    precise = 6
    for i in ansr:
        if type(i) is tuple: rstFlt += str([N(j, precise) for j in i]) + " \n"
        else: rstFlt += str(N(ansr[i], precise)) + ", " if type(ansr) is dict else str(N(i, precise)) + ", "
    result['float'] = rstFlt[:-2]
    return result

if __name__ == '__main__':
    a = 'ax^2+bx+c=0'
    b = ['x']
    expr = eq(a, b)
    print(expr)
    a = r'''\left\{ 
\begin{array}{c}
2x+3y+z=1 \\ 
2x+9y+5z=9 \\ 
x+3y+3z=3
\end{array}
\right.'''
    b = ['x', 'y', 'z']
    expr = eq(a, b)
    print(expr)
